<template>
  <div class="container container-table">
      <div class="row vertical-10p">
        <div class="container">
          <div class= "loginTitle">
            <span class="title">浙江省中波发射管理中心人事管理系统</span>
          </div>
          <!--<img src="/static/img/logo.png" class="center-block logo">-->
          <div class="text-center col-md-4 col-sm-offset-4">
            <!-- login form -->
            <form class="ui form loginForm">
              <el-alert v-if=error :title="info" type="error" style="padding:5px"></el-alert>
              <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                <input class="form-control" name="username" placeholder="用户名" type="text" v-model="username">
              </div>

              <div class="input-group">
                <span class="input-group-addon"><i class="fa fa-lock"></i></span>
                <input class="form-control" name="password" placeholder="********" type="password" v-model="password">
              </div>
               <div class="row">
                <el-button  type="primary" v-bind:class="'btn btn-primary btn-lg ' + loading" @click="checkCreds">  登  录  </el-button>
                <el-button  v-bind:class="'btn  btn-lg '" @click="forgetPwd">忘记密码</el-button>
              </div>
            </form>
            <!-- errors -->
          </div>
        </div>
      </div>
      <el-dialog title='设置密码' :visible.sync="needChangePwd" :modal="true" size="tiny"  width="60%" :before-close="()=>needChangePwd = false">
        <el-form :model="changePwdForm" status-icon :rules="rules2" ref="changePwdForm" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="pwdText" prop="oldpass">
            <el-input type="password" v-model="changePwdForm.oldpass" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="pass">
            <el-input type="password" v-model="changePwdForm.pass" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="checkPass">
            <el-input type="password" v-model="changePwdForm.checkPass" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="updatePass">确 定</el-button>
          </span>
      </el-dialog>
  </div>
</template>

<script>
import Utils from "../common/utils";
import sysConfigUtil from "../common/sysConfigUtil";
let util = new Utils();
let cnfUtil = new sysConfigUtil();
export default {
  name: "Login",
  data(router) {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.changePwdForm.checkPass !== "") {
          this.$refs.changePwdForm.validateField("checkPass");
        }
        callback();
      }
    };
    var strongValidate = (rule, value, callback) => {
      var pattern = /^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&*]+$)(?![a-zA-z\d]+$)(?![a-zA-z!@#$%^&*]+$)(?![\d!@#$%^&*]+$)[a-zA-Z\d!@#$%^&*]+$/;
      if (value.length < 8 || !pattern.exec(value)) {
        callback(new Error("密码强度不够,要求8位包含大小写,数字和特殊字符"));
      } else if (value === this.changePwdForm.oldpass) {
        callback(new Error("新密码不允许与老密码相同"));
      }else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认密码"));
      }else if (value !== this.changePwdForm.pass) {
        callback(new Error("两次输入密码不一致"));
      }
      else {
        callback();
      }
    };
    var required = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("输入为空,请输入"));
      } else {
        callback();
      }
    };
    return {
      section: "Login",
      needChangePwd: false,
      loading: "",
      username: "",
      password: "",
      response: "",
      changePwdForm: {
        oldpass: "",
        pass: "",
        checkPass: ""
      },
      error: false,
      info: "",
      smsAuth: false,
      pwdText: "旧密码",
      rules2: {
        oldpass: [
          { validator: required, trigger: "blur" },
          { validator: validatePass, trigger: "blur" }
        ],
        pass: [
          { validator: required, trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
          { validator: strongValidate, trigger: "blur" }
        ],
        checkPass: [
          { validator: required, trigger: "blur" },
          { validator: validatePass2, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.$nextTick(() => {
      this.loadSysConfig();
      this.loadDeparts()
    });
  },
  methods: {
    forgetPwd() {
      if (!this.username) {
        this.showTips("请输入登录账号!");
        return;
      }
      var that = this;
      util.sendSmsPwd(
        this.username,
        response => {
          if (response.body.result == 1) {
            util.showSucInfo(that, "验证码发送成功,请查收短信!");
            that.smsAuth = true;
            that.pwdText = "验证码";
            that.needChangePwd = true;
          } else {
            util.showErrorInfo(that, "验证码发送成功失败,请稍后重试!");
          }
        },
        response => {
          util.showErrorInfo(that, "网络异常,请稍后重试!");
          console.log("get user failed:" + response.data);
        }
      );
    },
    showTips(info) {
      this.info = info;
      this.error = true;
      var that = this;
      setTimeout(() => (this.error = false), 3000);
    },
    pwdVerify(pwd) {},
    checkCreds() {
      if (!this.username) {
        this.showTips("请输入登录账号!");
        return;
      }
      if (!this.password) {
        this.showTips("请输入登录密码!");
        return;
      }
      const { username, password } = this;

      this.toggleLoading();
      this.resetResponse();
      this.$store.commit("TOGGLE_LOADING");

      /* Making API call to authenticate a user */
      var that = this;
      util.login(
        username,
        password,
        response => {
          that.toggleLoading();

          var data = response.data;
          /* Checking if error object was returned from the server */
          if (data.result == 2) {
            this.showTips("账号密码不匹配请重新输入!");
          }
          if (data.result == 3) {
            this.showTips("账号不存在请重新输入!");
          } else if (data.result == 1) {
            /* Setting user in the state and caching record to the localStorage */
            var token = data.body.token;
            var graph = data.body.graph;
            var handle = data.body.handle;
            var submit = data.body.submit;
            var role = data.body.role;
            var user = {
              id: data.body.id,
              token: data.body.token,
              username: that.username,
              role: role
            };
            that.$store.commit("SET_USER", user);
            that.$store.commit("SET_GRAPH", graph);
            that.$store.commit("SET_HANDLE", handle);
            that.$store.commit("SET_SUBMIT", submit);

            if (window.sessionStorage) {
              window.sessionStorage.setItem("xLoginUser", JSON.stringify(user));
              window.sessionStorage.setItem("xGraph", JSON.stringify(graph));
              window.sessionStorage.setItem("xhandle", JSON.stringify(handle));
              window.sessionStorage.setItem("xsubmit", JSON.stringify(submit));
            }
            that.needChangePwd = data.body.lastLogin ? false : true;
            if (!that.needChangePwd) {
              if (that.$store.state.user.role.roles < 8) {
                that.$router.push("/users");
              } else that.$router.push("/dashboard");
            }
          }
        },
        response => {
          util.showErrorInfo(that, "网络异常,登录失败!");
        }
      );
    },
    toggleLoading() {
      this.loading = this.loading === "" ? "loading" : "";
    },
    resetResponse() {
      this.response = "";
    },
    loadDeparts(){
       var that = this;
       cnfUtil.listDeparts(
        response => {
          console.log("加载配置" + JSON.stringify(response.body));
          if (window.sessionStorage) {
            window.sessionStorage.setItem(
              "departs",
              JSON.stringify(response.body.body)
            );
          }
          that.$store.commit('SET_DEPARTS',response.body.body )
          // that.$store.commit("SET_SYSCONFIG",response.body.body)
        },
        response => {
          util.showErrorInfo(that, "加载系统配置出错,请刷新!");
        }
      );
    },
    loadSysConfig() {
      var that = this;
      cnfUtil.listAll(
        response => {
          console.log("加载配置" + JSON.stringify(response.body));
          if (window.sessionStorage) {
            window.sessionStorage.setItem(
              "sysconfig",
              JSON.stringify(response.body.body)
            );
          }
          // that.$store.commit("SET_SYSCONFIG",response.body.body)
        },
        response => {
          util.showErrorInfo(that, "加载系统配置出错,请刷新!");
        }
      );
    },
    updatePass() {
      this.$refs.changePwdForm.validate(
        function(result) {
          var that = this;
          if (result) {
            util.changePwd(
              this.username,
              this.changePwdForm.oldpass,
              this.changePwdForm.pass,
              this.smsAuth,
              response => {
                if (response.body.result == 1) {
                  util.showSucInfo(that, "更新密码成功,请登录!");
                  that.smsAuth = false;
                  that.pwdText = "旧密码";
                  that.needChangePwd = false;
                }else if(response.body.result == 10){
                  util.showErrorInfo(that, "设置密码不能与之前密码一致!");
                } 
                else {
                  util.showErrorInfo(that, "更新密码失败!");
                }
              },
              response => {
                util.showErrorInfo(that, "网络异常,请稍后重试!");
                console.log("get user failed:" + response.data);
              }
            );
          } else {
            util.showErrorInfo(that,"密码强度不够,要求8位包含大小写,数字和特殊字符!");
          }
        }.bind(this)
      );
    }
  }
};
</script>

<style>
html,
body,
.container-table {
  height: 100%;
  /*background-color: #282B30 !important;*/
}

body {
  background-image: url("/static/img/background.jpg");
  background-size: cover;
}

.container-table {
  display: table;
}
.vertical-center-row {
  display: table-cell;
  vertical-align: middle;
}
.vertical-20p {
  padding-top: 20%;
}
.vertical-10p {
  padding-top: 10%;
}
/*.logo {
  width: 15em;
  padding: 3em;
}*/
.loginForm .input-group {
  padding-bottom: 1em;
  height: 4em;
}
.input-group input {
  height: 4em;
}
.loginTitle {
  display: block;
  margin-top: 80px;
  color: white;
  margin-right: auto;
  margin-left: auto;
  text-align: center;
  margin-bottom: 80px;
}
.title {
  display: inline;
  font-size: 50px;
}
.el-dialog--small {
  width: 200px;
}
</style>
